﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data;

namespace DataModel.DBService.Impl
{
    public abstract class RepositoryBase<T> : IRepository<T> where T : class,new()
    {
        public DbContext context;

        //提供IOC注入方式接口
        public RepositoryBase()
        {
            context = new ProductDBContext();
        }


        public virtual T Create()
        {
            return context.Set<T>().Create();
        }

        public virtual T Update(T entity)
        {
            //执行验证业务
            //context.Entry<T>(entity).GetValidationResult();
            if (context.Entry<T>(entity).State == EntityState.Modified)
                context.SaveChanges();
            return entity;
        }

        public virtual T Insert(T entity)
        {
            try
            {
                context.Set<T>().Add(entity);
                context.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
            return entity;
        }

        public virtual void Delete(T entity)
        {
            try
            {
                context.Set<T>().Remove(entity);
                context.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public virtual T Find(params object[] keyValues)
        {
            return context.Set<T>().Find(keyValues);
        }

        public virtual List<T> FindAll()
        {
            return context.Set<T>().ToList();
        }
    }
}
